package cn.edu.swufe.stu2025.finalwork;

import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class BacklogAdapter extends RecyclerView.Adapter<BacklogAdapter.ViewHolder> {
    private List<BacklogItem> data;
    private Set<Integer> selected = new HashSet<>();
    private boolean multiSelectMode = false;
    private MultiSelectListener multiSelectListener;
    private OnItemClickListener itemClickListener;
    private boolean hideCompleted = false; // 控制是否隐藏已完成

    public interface MultiSelectListener {
        void onMultiSelectModeChanged(boolean enabled);
    }
    public void setMultiSelectListener(MultiSelectListener listener) {
        this.multiSelectListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.itemClickListener = listener;
    }

    public BacklogAdapter(List<BacklogItem> data) {
        this.data = data;
    }

    public void setHideCompleted(boolean hide) {
        this.hideCompleted = hide;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LinearLayout layout = new LinearLayout(parent.getContext());
        layout.setOrientation(LinearLayout.HORIZONTAL);
        Button btn = new Button(parent.getContext());
        btn.setId(View.generateViewId());
        btn.setText("○");
        btn.setBackgroundResource(R.drawable.circle_button);
        btn.setTextSize(20);
        btn.setAllCaps(false);
        btn.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        TextView text = new TextView(parent.getContext());
        text.setId(View.generateViewId());
        text.setLayoutParams(new LinearLayout.LayoutParams(
                0, ViewGroup.LayoutParams.MATCH_PARENT, 1));
        layout.addView(btn);
        layout.addView(text);
        return new ViewHolder(layout, text, btn);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // 过滤已完成项
        int realPos = getRealPosition(position);
        BacklogItem item = data.get(realPos);

        holder.text.setText(item.content);
        // 状态按钮样式
        if (item.completed) {
            holder.btn.setText("✔");
            holder.btn.setBackgroundColor(Color.parseColor("#CCA27E45")); // 深色
            holder.text.setTextColor(Color.GRAY);
            holder.itemView.setBackgroundColor(Color.parseColor("#E0E0E0")); // 加深
        } else {
            holder.btn.setText("○");
            holder.btn.setBackgroundColor(Color.parseColor("#EDD7A7")); // 浅色
            holder.text.setTextColor(Color.BLACK);
            holder.itemView.setBackgroundColor(selected.contains(realPos) ? Color.LTGRAY : Color.WHITE);
        }

        holder.btn.setOnClickListener(v -> {
            if (!item.completed) {
                item.completed = true;
                data.remove(realPos);
                data.add(item); // 移到底部
                notifyDataSetChanged();
            } else {
                item.completed = false;
                data.remove(realPos);
                data.add(0, item); // 移到顶部
                notifyDataSetChanged();
            }
        });

        holder.itemView.setOnLongClickListener(v -> {
            if (!multiSelectMode) {
                multiSelectMode = true;
                selected.clear();
                selected.add(realPos);
                notifyDataSetChanged();
                if (multiSelectListener != null) multiSelectListener.onMultiSelectModeChanged(true);
            }
            return true;
        });

        holder.itemView.setOnClickListener(v -> {
            if (multiSelectMode) {
                toggleSelection(realPos);
            } else {
                if (itemClickListener != null) itemClickListener.onItemClick(realPos);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (!hideCompleted) return data.size();
        int count = 0;
        for (BacklogItem item : data) {
            if (!item.completed) count++;
        }
        return count;
    }

    // 获取实际数据索引（过滤已完成项时用）
    private int getRealPosition(int adapterPosition) {
        if (!hideCompleted) return adapterPosition;
        int idx = -1, shown = -1;
        for (int i = 0; i < data.size(); i++) {
            if (!data.get(i).completed) {
                shown++;
                if (shown == adapterPosition) {
                    idx = i;
                    break;
                }
            }
        }
        return idx;
    }

    public void toggleSelection(int pos) {
        if (selected.contains(pos)) {
            selected.remove(pos);
        } else {
            selected.add(pos);
        }
        notifyItemChanged(pos);
        if (selected.isEmpty()) {
            multiSelectMode = false;
            if (multiSelectListener != null) multiSelectListener.onMultiSelectModeChanged(false);
            notifyDataSetChanged();
        }
    }

    public void deleteSelected() {
        List<Integer> toDelete = new java.util.ArrayList<>(selected);
        java.util.Collections.sort(toDelete, java.util.Collections.reverseOrder());
        for (int pos : toDelete) {
            data.remove(pos);
        }
        selected.clear();
        multiSelectMode = false;
        notifyDataSetChanged();
        if (multiSelectListener != null) multiSelectListener.onMultiSelectModeChanged(false);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView text;
        Button btn;
        ViewHolder(View itemView, TextView text, Button btn) {
            super(itemView);
            this.text = text;
            this.btn = btn;
        }
    }
}